package com.zoro.interviewee.fj;

import java.util.concurrent.*;

/**
 * @author zhaoxingwu
 */
public class ForkJoinTest {

    /**
     * 计算从整数A到整数B的累加和
     *
     * @param args args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        int from = 1, to = 1000;

        ForkJoinPool pool = new ForkJoinPool();
        long start = System.nanoTime();
        ForkJoinTask<Integer> result = pool.submit(new MyTask(from, to));
        int result1 = result.get();
        long end = System.nanoTime();
        System.out.printf("结果：%s, 分解用时间，%s %n", result1, (end - start));

        long s = System.nanoTime();
        int testResult = 0;
        for (int i = from; i <= to; i++) {
            testResult += i;
            TimeUnit.MILLISECONDS.sleep(10);
        }
        long e = System.nanoTime();
        System.out.printf("结果：%s, 不分解用时，%s", testResult, (e - s));
    }
}

/**
 * 每个任务计算的量不能超过10 ，超过就分解成小的
 */
class MyTask extends RecursiveTask<Integer> {

    private final int from;
    private final int to;

    public MyTask(int from, int to) {
        this.from = from;
        this.to = to;
    }

    @Override
    protected Integer compute() {

        if (to - from > 50) {

            int thisTo = (to + from) / 2;
            MyTask t1 = new MyTask(from, thisTo);
            MyTask t2 = new MyTask(thisTo + 1, to);
            t1.fork();
            t2.fork();
            Integer i1 = t1.join();
            Integer i2 = t2.join();
            return i1+i2;

        } else {
            System.out.printf("不需要分解, %s,%s %n", from, to);
            int result = 0;
            for (int i = from; i <= to; i++) {
                result += i;
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            return result;
        }

    }
}
